<?php
namespace control;
//管理员后台 - 外部联系人
class contactsClass extends adIndexClass
{
    private const page = 'contacts'; # 权限
    private const table = 'contacts'; # 数据表
    private const title = '公共通讯录';

    /*外部联系人-查询条件*/
    public function home()
    {
        $html =
            text(["name" => "companyName", "title" => L('person.table.dwmc')]) .
            text(["name" => "name", "title" => L('person.table.xing_ming')]) .
            text(["name" => "tel", "title" => L('person.table.shou_ji_hao')]);
        //返回
        return $this->homeFun($this->search($html));
    }

    /*外部联系人-查询结果*/
    public function homeSearch()
    {
        $where = " type='公共通讯录' ";
        $equal = [
        ];
        $like = [
            'companyName' => $this->post('companyName'),
            'name' => $this->post('name'),
            'tel' => $this->post('tel'),
        ];
        $where .= search([
            "=" => $equal,
            "like" => $like,
        ]);

        $orderBy = ' time DESC';
        //获取查询结果
        $page = $this->page([
            "table" => self::table,
            "where" => $where,
            "order" => $orderBy,
        ]);
        //获取表头
        $checkAll = $this->checkAll("listForm", "id");
        $tr[] = [$checkAll, L('person.table.dwmc'), L('person.table.xing_ming'), L('person.table.xing_bie'), L('person.table.zhi_wei'), L('person.table.shou_ji_hao'), L('person.table.wei_xin'), 'QQ', L('person.table.bei_zhu'), L('person.table.gxsj')];
        //获取记录
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail";

        foreach ($page['array'] as $array) {
            $dominate = [
                "box" => [
                    "name" => "id",
                    "value" => $array['id']
                ],
                "detail" => [
                    "title" => L('person.table.lxrxq'),
                    "click" => "newIframe('" . L('person.table.xjlxr') . "','" . $url . "&id=" . $array['id'] . "')"
                ],
            ];
            $tr[] = [$this->dominate($dominate), $array['companyName'], $array['name'], $array['gender'], $array['position'], $array['tel'], $array['wechat'], self::null($array['qq']), $array['text'], $array['updateTime']];
        }
        //控件
        $button = '';
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"newIframe('" . L('person.table.xjlxr') . "', '" . $this->root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=editPage')\">" . L('salary.table.xin_zeng') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('salary.table.shan_chu') . "</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 获取角色名称
     *
     * @param string $ids
     */
    public static function getRoleName($ids)
    {
        $roleName = '';
        $roleArray = json_decode($ids, true);
        foreach ($roleArray as $rid) {
            $role = query('role', " id = '$rid' ");
            $roleName .= $role['name'] ? ($role['name'] . ';') : '';
        }
        return $roleName;
    }


    /**
     * 新建
     *
     * @return void
     */
    public function detail()
    {
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $html = L('person.table.nmzckzx');
        } elseif (!$this->get('id')) {
            $html = "ID为空";
        } elseif (!$info['id']) {
            $html = L('person.table.wzdcxx');
        } else {
            $data = [
                "id" => $info['id'],
            ];
            //按钮
            $button = [];
            if ($this->power(self::page, "edit")) {
                $button[] = [
                    "name" => L('person.table.shan_chu'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
                $button[] = [
                    "name" => L('person.table.bian_ji'),
                    "type" => "顶部页卡",
                    "title" => L('person.table.bian_ji'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            //生成表单
            $data['html'] = $this->tableShow([
                "button" => $button,
                L('person.table.ji_ben_xin_xi') => [
                    [
                        L('person.table.dwmc') => $info['name'],
                        L('person.table.xing_ming') => $info['name'],
                        L('person.table.xing_bie') => $info['gender'],
                    ],
                    [
                        L('person.table.zhi_wei') => $info['position'],
                        L('person.table.shou_ji_hao') => $info['tel'],
                        L('person.table.wei_xin') => $info['wechat'],
                    ],
                    [
                        "QQ" => self::null($info['qq']),
                    ],
                    [
                        L('person.table.bei_zhu') => "<pre>" . kong($info['text']) . "</pre>",
                    ],
                ],
                L('person.table.xi_tong_xin_xi') => [
                    [
                        L('person.table.lxrbh') => $info['orderNo'],
                        L('person.table.chuang_jian_ren') => self::findStaff($info['stid'], 'name'),
                        L('person.table.cjsj') => $info['time'],
                    ],
                    [
                        L('person.table.gxsj') => $info['updateTime'],
                    ],
                ]
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    public function editPage()
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    must . L('person.table.dwmc') => text(['name' => "companyName", 'class' => 'text', 'value' => $info['companyName']]),
                ],
                [
                    must . L('person.table.xing_ming') => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
                ],
                [
                    must . L('person.table.xing_bie') => radio(['name' => "gender", 'value' => ['男', '女', '未知'], 'checked' => $info['gender']]),
                ],
                [
                    must . L('person.table.zhi_wei') => text(['name' => "position", 'class' => 'text', 'value' => $info['position']]),
                ],
                [
                    must . L('person.table.shou_ji_hao') => text(['name' => "tel", 'class' => 'text', 'value' => $info['tel']]),
                ],
                [
                    L('person.table.wei_xin') => text(['name' => "wechat", 'class' => 'text', 'value' => $info['wechat']]),
                ],
                [
                    'QQ' => text(['name' => "qq", 'class' => 'text', 'value' => $info['qq']]),
                ],
                [
                    L('person.table.bei_zhu') . "：" => textarea(["name" => "text", "value" => $info['text']])
                        . hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
                ],
            ],
            'button' => '<button class="button left-bottom" onclick="subForm(\'' . $this->get('cla') . 'EditPageForm\',root+\'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPageEdit\')">' . L('salary.table.bao_cun') . '</button>',
        ]);
        $html = '';
        //返回
        return $this->tab($data) . $html;
    }


    /*成本表基本资料新增或修改-异步处理*/
    public function editPageEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'companyName' => $this->post('companyName'),
            'name' => $this->post('name'),
            'gender' => $this->post('gender'),
            'position' => $this->post('position'),
            'tel' => $this->post('tel'),
            'wechat' => $this->post('wechat'),
            'qq' => $this->post('qq'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'companyName' => L('person.table.dwmc'),
            'name' => L('person.table.xing_ming'),
            'gender' => L('person.table.xing_bie'),
            'position' => L('person.table.zhi_wei'),
            'tel' => L('person.table.shou_ji_hao'),
            'wechat' => L('person.table.wei_xin'),
            'qq' => 'QQ',
            'text' => L('person.table.bei_zhu'),
        ];
        $rules = [
            'companyName' => 'required',
            'name' => 'required',
            'gender' => 'required',
            'position' => 'required',
            'tel' => 'required|tel',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('person.table.publicBookEdit');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (sqlNum(self::table, " (name = '{$field['name']}' AND tel = '{$field['tel']}') AND id <> '$id'   ") > 0) {
                $json['warn'] = str_replace(['{{name}}}', '{{tel}}}'], [$field['name'], $field['tel']], L('person.table.publicBookEditWarn'));
                goto resp;
            }
            if (!$info['id']) {
                $orderNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'LM',
                    'type' => '公共通讯录',
                    'table' => 'contacts',
                    'field' => 'orderNo',
                    'default' => '00001',
                    'where' => '',
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $orderNo,
                    'type' => '公共通讯录',
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $field['name']], L('person.table.publicBookEditText'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('person.table.publicBookDel');
                $title = self::table . 'Delete';
                $function = 'isDelete';
                $form = $this->get('cla') . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('job.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    // 确认删除信息
    public function isDelete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('person.table.publicBookDelPermission');
        } elseif (empty($array)) {
            $json['warn'] = L('person.table.nytjldmzxzn');
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if ($info['id']) {
                    // 删除表
                    delete([
                        "table" => self::table,
                        "where" => $where
                    ]);
                    //添加记录
                    $text .= str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $info['name']], L('person.table.publicBookDelText')) . "<br>";
                    $x++;
                }
            }
            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('person.table.publicBookDelWarn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }

        resp:
        return json_encode($json, 320);
    }
}
